#!/bin/bash

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m' # 无颜色

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
if [ "$(id -u)" != "0" ]; then
   log_error "此脚本必须以root权限运行" 
   exit 1
fi

# 默认的数据库配置
DB_NAME="boxuser"
DB_USER="boxuser"
DB_PASSWORD=""
DB_HOST="localhost"
DB_PORT="3306"
MYSQL_ROOT_PASSWORD=""

# 提示用户输入数据库信息或使用默认值
read -p "MySQL root密码: " MYSQL_ROOT_PASSWORD
if [ -z "$MYSQL_ROOT_PASSWORD" ]; then
    log_error "MySQL root密码不能为空"
    exit 1
fi

read -p "数据库名称 (默认: $DB_NAME): " input
DB_NAME=${input:-$DB_NAME}

read -p "数据库用户名 (默认: $DB_USER): " input
DB_USER=${input:-$DB_USER}

read -p "数据库密码: " DB_PASSWORD
if [ -z "$DB_PASSWORD" ]; then
    log_error "数据库密码不能为空"
    exit 1
fi

read -p "数据库主机 (默认: $DB_HOST): " input
DB_HOST=${input:-$DB_HOST}

read -p "数据库端口 (默认: $DB_PORT): " input
DB_PORT=${input:-$DB_PORT}

# 安装MySQL
log_info "正在安装MySQL服务器..."
if [ -f /etc/redhat-release ]; then
    # CentOS/RHEL
    yum -y install mysql-server mysql || {
        log_error "MySQL安装失败"
        exit 1
    }
    systemctl start mysqld
    systemctl enable mysqld
elif [ -f /etc/debian_version ]; then
    # Debian/Ubuntu
    apt-get update
    apt-get -y install mysql-server || {
        log_error "MySQL安装失败"
        exit 1
    }
    systemctl start mysql
    systemctl enable mysql
else
    log_error "不支持的操作系统"
    exit 1
fi

# 检查MySQL是否安装成功
if ! command -v mysql &> /dev/null; then
    log_error "MySQL未成功安装"
    exit 1
fi

log_info "MySQL服务器已安装"

# 检查MySQL服务是否在运行
if ! systemctl is-active --quiet mysql && ! systemctl is-active --quiet mysqld; then
    log_error "MySQL服务未运行"
    exit 1
fi

log_info "MySQL服务正在运行"

# 创建数据库和用户
log_info "创建数据库和用户..."

# MySQL安全设置
mysql_secure_installation_sql="
UPDATE mysql.user SET Password=PASSWORD('${MYSQL_ROOT_PASSWORD}') WHERE User='root';
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
"

# 数据库和用户创建SQL
create_db_sql="
CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${DB_USER}'@'%' IDENTIFIED BY '${DB_PASSWORD}';
GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'%';
FLUSH PRIVILEGES;
"

# 执行安全设置（如果是全新安装）
if [ -f /var/lib/mysql/mysql_secure_installation ]; then
    log_info "MySQL已经进行过安全设置，跳过"
else
    log_info "执行MySQL安全设置..."
    mysql -u root -e "$mysql_secure_installation_sql" || {
        log_warn "MySQL安全设置失败，可能已经设置过密码"
        
        # 尝试使用root密码
        mysql -u root -p"${MYSQL_ROOT_PASSWORD}" -e "SELECT 1" &>/dev/null || {
            log_error "无法连接到MySQL，请检查root密码"
            exit 1
        }
    }
    touch /var/lib/mysql/mysql_secure_installation
fi

# 创建数据库和用户
log_info "创建数据库 ${DB_NAME} 和用户 ${DB_USER}..."
mysql -u root -p"${MYSQL_ROOT_PASSWORD}" -e "$create_db_sql" || {
    log_error "创建数据库和用户失败"
    exit 1
}

# 验证数据库和用户
log_info "验证数据库连接..."
mysql -u "${DB_USER}" -p"${DB_PASSWORD}" -h "${DB_HOST}" -P "${DB_PORT}" -e "USE \`${DB_NAME}\`; SELECT 'Connection successful!';" || {
    log_error "数据库连接验证失败"
    exit 1
}

# 更新.env文件
log_info "更新环境变量配置..."
APP_DIR="/var/www/box-user"
ENV_FILE="${APP_DIR}/.env"

# 检查.env文件是否存在
if [ ! -f "$ENV_FILE" ]; then
    log_warn "环境变量文件不存在: ${ENV_FILE}"
    log_info "创建新的环境变量文件..."
    mkdir -p "$(dirname "$ENV_FILE")"
    touch "$ENV_FILE"
fi

# 更新数据库配置
cat > "$ENV_FILE" << EOF
DB_NAME=${DB_NAME}
DB_USER=${DB_USER}
DB_PASSWORD=${DB_PASSWORD}
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
SECRET_KEY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9!@#$%^&*()-_=+' | head -c 50)
DEBUG=False
ALLOWED_HOSTS=*,localhost,127.0.0.1
EOF

log_info "环境变量已更新: ${ENV_FILE}"

# 配置MySQL的性能和安全设置
log_info "配置MySQL性能和安全设置..."
MYSQL_CNF="/etc/mysql/my.cnf"
if [ ! -f "$MYSQL_CNF" ]; then
    MYSQL_CNF="/etc/my.cnf"
fi

if [ -f "$MYSQL_CNF" ]; then
    # 备份原始配置
    cp "$MYSQL_CNF" "${MYSQL_CNF}.bak"
    
    # 添加性能和安全配置
    cat >> "$MYSQL_CNF" << EOF

# 妙趣拾光锦盒项目的性能和安全设置
[mysqld]
# 性能设置
innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
max_connections = 100
key_buffer_size = 32M
table_open_cache = 400
query_cache_size = 32M

# 字符集和排序规则
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

# 安全设置
max_allowed_packet = 16M
bind-address = 0.0.0.0
symbolic-links = 0

# 日志设置
log_error = /var/log/mysql/error.log
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
EOF

    # 创建日志目录
    mkdir -p /var/log/mysql
    chown mysql:mysql /var/log/mysql

    # 重启MySQL服务
    log_info "重启MySQL服务..."
    if systemctl is-active --quiet mysqld; then
        systemctl restart mysqld
    else
        systemctl restart mysql
    fi
else
    log_warn "未找到MySQL配置文件，跳过性能设置"
fi

log_info "MySQL数据库设置完成!"
log_info "数据库名称: ${DB_NAME}"
log_info "数据库用户: ${DB_USER}"
log_info "数据库主机: ${DB_HOST}:${DB_PORT}"
log_info ""
log_info "请确保Django应用的.env文件包含了正确的数据库连接信息" 